import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Select, Table, TableProps} from 'antd';
import type {Facility} from "@/types/resp/facility";
import facilityApi from '@/api/facilityApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";


interface FacilitySelectorProps {
  visible: boolean;
  onFacilitySelected: (selectedFacility: { facilityId?: number; facilityName?: string; }) => void;
  onCloseFacilitySelector: () => void;
}

const FacilitySelector: React.FC<FacilitySelectorProps> = ({visible, onFacilitySelected, onCloseFacilitySelector}) => {

  const [facilitySelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    facilitySelectorForm.resetFields();
  };

  const [data, setData] = useState<Facility[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Facility>> = await facilityApi.find(facilitySelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Facility> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Facility>['columns'] = [
    {title: '公共设施名称', dataIndex: 'name', key: 'name'},
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '位置', dataIndex: 'location', key: 'location'},
    {title: '最后保养日期', key: 'lastMaintenanceDate', render: (_, record) => (
      <div>{record.lastMaintenanceDate.format('YYYY-MM-DD')}</div>
    )},
    {title: '状态', key: 'status', render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '正常';
          else if (record.status === 20) return '异常';
          else return '未知';
        })()}
      </span>
      ),
    },
  ];

  const handleRowDoubleClick = (row: Facility) => {
    onFacilitySelected({
      facilityId: row.id,
      facilityName: row.name,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseFacilitySelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      facilitySelectorForm.setFieldsValue(Object.assign(facilitySelectorForm.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };

  return (
    <Modal title={"公共设施信息选择器(双击行选中)"} open={visible} onCancel={onCloseFacilitySelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={facilitySelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="name" label="公共设施名称">
          <Input maxLength={255} placeholder="请输入公共设施名称"/>
        </Form.Item>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
        </Form.Item>
        <Form.Item name="location" label="位置">
          <Input maxLength={255} placeholder="请输入位置"/>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" options={[
            { value: 10, label: <span>正常</span> },
            { value: 20, label: <span>异常</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Facility> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
    </Modal>
  );
};

export default FacilitySelector;
